package com.micai.boss.weixin.repository;

import com.alibaba.fastjson.JSON;
import com.micai.boss.base.constant.ErrorCodeEnum;
import com.micai.boss.base.exception.ServiceException;
import com.micai.boss.base.utils.AssertUtils;
import com.micai.boss.weixin.constant.WeiXinConstant;
import com.micai.boss.weixin.service.dto.SnsAuthDto;
import com.micai.boss.weixin.util.WeixinUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/4/19 17:12
 */
@Repository
public class WeiXinRepository extends AbstractWeiXinRepository {

    private Logger logger = LoggerFactory.getLogger(WeiXinRepository.class);

    @Override
    protected String getRedisKey() {
        return "WEIXIN_KEY";
    }

    @Value("${weixin.appid}")
    private String app_id;

    @Value("${weixin.appsecret}")
    private String app_secret;

    private static final String wxscopeAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";

    public SnsAuthDto getScopeAccessToken(String code){
        AssertUtils.notNull(code, ErrorCodeEnum.参数为空.getMessage());
//        https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
//        access_tokenUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
        String cache_token = (String) super.get(WeiXinConstant.WX_CACHE_SCOPE_TOKEN_KEY + code);
        if(!StringUtils.isEmpty(cache_token) ){
            return JSON.parseObject(cache_token,SnsAuthDto.class);
        }
        StringBuffer access_tokenUrl = new StringBuffer();
        access_tokenUrl.append(wxscopeAccessTokenUrl + "?appid=");
        access_tokenUrl.append(app_id);
        access_tokenUrl.append("&secret=" + app_secret);
        access_tokenUrl.append("&code=" + code);
        access_tokenUrl.append("&grant_type=authorization_code");
        String url = access_tokenUrl.toString();
        logger.info("getScopeAccessToken requstUrl:{}",url);
        String response = WeixinUtil.httpsRequestWithStringReturn(url,"GET",null);
        logger.info("getScopeAccessToken response:{}",response);
        if(StringUtils.isEmpty(response)){
            throw new ServiceException(ErrorCodeEnum.系统异常.getCode(),"授权获取网页token失败");
        }
        SnsAuthDto snsAuthDto = JSON.parseObject(response,SnsAuthDto.class);
        String expires = snsAuthDto.getExpires_in();
        if(!StringUtils.isEmpty(expires)){
            super.put(WeiXinConstant.WX_CACHE_SCOPE_TOKEN_KEY + code,response,Integer.parseInt(expires)/60);
        }
        return snsAuthDto;
    }


}
